package article

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/algorithm/treenode"
	"gitee.com/bobo-rs/creative-services/enums"
	"gitee.com/bobo-rs/creative-services/framework/dao"
	"gitee.com/bobo-rs/creative-services/framework/model"
	"gitee.com/bobo-rs/creative-services/framework/model/entity"
	"gitee.com/bobo-rs/creative-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
)

// SaveCategory 保存文章分类数据
func (a *sArticle) SaveCategory(ctx context.Context, item entity.ArticleCategory) error {
	// 保存数据
	_, err := dao.ArticleCategory.Ctx(ctx).
		OmitEmpty().
		Save(item)
	if err != nil {
		return exception.New(`保存文章分类错误`)
	}
	return nil
}

// GetCategoryTreeList 获取文章分类树形列表
func (a *sArticle) GetCategoryTreeList(ctx context.Context, where interface{}) ([]map[string]interface{}, error) {
	var (
		rows []model.ArticleCategoryListItem
		err  error
	)
	// 查询条件nil则默认全部
	if where == nil {
		where = g.Map{}
	}

	// 查询条件
	err = a.CategoryModel().Scan(ctx, where, &rows)
	if err != nil {
		return nil, err
	}

	// 数据为空
	if len(rows) == 0 {
		return nil, exception.New(`暂无数据`)
	}

	// 构造树形结构
	return treenode.New().BuildTree(rows)
}

// GetCategoryAssocTreeList 获取文章分类关联列表
func (a *sArticle) GetCategoryAssocTreeList(ctx context.Context) ([]map[string]interface{}, error) {
	return a.GetCategoryTreeList(ctx, g.Map{
		dao.ArticleCategory.Columns().Status: enums.ArtCategoryStatusOk,
	})
}
